package com.huyi.web.controller;

import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huyi.common.result.APIResponse;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
@RequestMapping("/kafka")
public class KafkaController {
   
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    @Value("${kafka.consumer.topic}")
    private String topic;


	@ApiOperation(value = "kafka发送消息")
	@RequestMapping(value = "/send/{message}", method = RequestMethod.GET)
	@ResponseBody
    public JSONObject sendKafka(HttpServletRequest request, @PathVariable("message") String message) throws InterruptedException, ExecutionException {
        log.info("kafka的消息={}", message);
        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, message);
        SendResult<String,String> sendResult = future.get();
        future.addCallback(
        		SuccessCallback -> {log.info("kafka Producer发送消息成功！topic=" + sendResult.getRecordMetadata().topic()+",partition"+sendResult.getRecordMetadata().partition()+",offset="+sendResult.getRecordMetadata().offset());},
        		FailureCallback -> {log.error("kafka Producer发送消息失败！sendResult=" + JSON.toJSONString(sendResult.getProducerRecord()));}
        );
        return APIResponse.returnSuccess();
    }

}